<?php

declare(strict_types=1);

namespace App\Exchange\Process;

use Carbon\Carbon;
use Hyperf\Process\AbstractProcess;
use Hyperf\Process\Annotation\Process;
use Hyperf\Redis\Redis;
use Hyperf\WebSocketClient\Client;
use Hyperf\WebSocketClient\ClientFactory;
use Hyperf\WebSocketClient\Frame;

#[Process(name: 'BinanceMiniTickerProcess')]
class BinanceMiniTickerProcess extends AbstractProcess
{
    public Client $client;
    public int $start_at;
    public Redis $redis;

    public function stop(): bool
    {
        return $this->client->close();
    }

    public function isEnable($server): bool
    {
        return false;
        return env('APP_ENV') == 'prod';
    }

    public function handle(): void
    {
        $this->redis = container()->get(Redis::class);
        $this->start();
    }

    public function initClient(): void
    {
        $this->start_at = Carbon::now()->getTimestampMs();

        $host = 'wss://stream.binance.com/ws/trxusdt@miniTicker';
        $this->client = container()->get(ClientFactory::class)->create($host, false);
        $subscribe = [
            'method' => 'SUBSCRIBE',
            'params' => [
                'ton@miniTicker',
                'eth@miniTicker',
            ],
            'id' => time()
        ];
        $this->client->push(json_encode($subscribe));
    }

    public function formatData(): void
    {
        while (true) {
            /** @var $msg Frame */
            $msg = $this->client->recv(1);
            if (!$msg instanceof Frame) continue;
            $res = json_decode($msg->data, true);
            print_r($res);
            if ($res['E'] - $this->start_at > 7200000) {
                $this->stop();
                break;
            }
//            $this->redis->hSet();
        }
    }

    public function start(): void
    {
        $this->initClient();
        $this->formatData();
        $this->start();
    }
}
